package zhoug.common.utils;


import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import zhoug.logging.Logger;

/**
 * 防抖
 *
 * @Author: zhoug
 * @Date: 2024-10-14
 * @Description:
 */
public class AntiShakeHelper {
    private static final String TAG = ">>>AntiShakeHelper";
    private Map<String, Long> mCache;
    private long mIntervalTime = 300;//2次执行任务的最小间隔时间

    public AntiShakeHelper() {
        mCache = new HashMap<>();
    }

   /* public AntiShakeHelper(LifecycleOwner lifecycleOwner) {
        if (lifecycleOwner != null) {
            lifecycleOwner.getLifecycle().addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onCreate(@NonNull LifecycleOwner owner) {
                    mCache = new HashMap<>();
                }

                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    clear();
                }
            });
        }
    }*/

    public void setIntervalTime(long mIntervalTime) {
        this.mIntervalTime = mIntervalTime;
    }

    public void execute(@NonNull Task task) {
        String evenId = task.evenId();
        if (mCache!=null && evenId != null && mIntervalTime > 0) {
            //现在时间
            long currentTime = System.currentTimeMillis();
            Long last = mCache.get(evenId);
            //上次时间
            long lastTime = last != null ? last : 0;
            if (lastTime > 0 && currentTime - lastTime <= mIntervalTime) {
                Logger.e(TAG, "2次执行时间少于:" + mIntervalTime);
                return;
            }
            mCache.put(evenId, currentTime);
        }
        task.run();
    }


    public interface Task {
        /**
         * 标记任务唯一id
         * @return
         */
        String evenId();

        void run();
    }

    public void clear() {
        if (mCache != null) {
            mCache.clear();
        }
    }

}
